package com.xxkj.drugtraceability.ui.tracdetail

import android.app.Application
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.xxhis.drugtraceability.base.BaseViewModel
import com.xxkj.drugtraceability.bean.*
import com.xxkj.drugtraceability.net.Result
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * author: zhoujingjin
 * created on: 2024/9/10 16:15
 * description:
 */
class TracDetailViewModel(application: Application, private val repository: TracRepository):BaseViewModel(application) {
    var prescriptioninfo = mutableListOf<DoctorAdviceInfoBean>()
    var showList =  MutableLiveData<List<DrugInfoBean>>()
    var baseUiModel = MutableLiveData<BaseUiModel<Boolean>>()
    //是否可以扫溯源码，如果处方码已经保存过追溯码，无论保存的多少，都不再让保存了。
    var canAdd = true
    var selectIndex = MutableLiveData(-1)
    var lastIndex = -1
    var barcode = ""
    var Prescriptionbarcode = ""
    var uiState = MutableLiveData<UiState<Boolean>>()
    /**
     * 获取病人某个时间的医嘱列表
     */
    fun tracCodedetail(id:String?,tradeType:String){
        viewModelScope.launch(Dispatchers.Main) {
            withContext(Dispatchers.IO) {
                uiState.postValue(UiState(isLoading = true))
                val result = repository.tracCodedetail(id,tradeType)
                if (result is Result.Success){
                    //获取成功了
                    showList.postValue(result.data.data)
                    uiState.postValue(UiState(isLoading = false))
                }else if (result is Result.Error){
                    uiState.postValue(UiState(isLoading = false,isError = result.errorData?:result.exception.message))
                }
            }}
    }
  fun tracCodeModify(data:String){
        viewModelScope.launch(Dispatchers.Main) {
            withContext(Dispatchers.IO) {
                uiState.postValue(UiState(isLoading = true))
                val result = repository.tracCodeModify(data)
                if (result is Result.Success){
                    //获取成功了
                    uiState.postValue(UiState(isLoading = false,isSuccess = true))
                }else if (result is Result.Error){
                    uiState.postValue(UiState(isLoading = false,isError = result.errorData?:result.exception.message))
                }
            }}
    }
 fun tracCodeUpload(data:String){
        viewModelScope.launch(Dispatchers.Main) {
            withContext(Dispatchers.IO) {
                uiState.postValue(UiState(isLoading = true))
                val result = repository.tracCodeUpload(data)
                if (result is Result.Success){
                    //获取成功了
                    uiState.postValue(UiState(isLoading = false,isSuccess = true))
                }else if (result is Result.Error){
                    uiState.postValue(UiState(isLoading = false,isError = result.errorData?:result.exception.message))
                }
            }}
    }
    fun trugTracCodgIsGather(barcode:String){
        viewModelScope.launch(Dispatchers.Main) {
            withContext(Dispatchers.IO) {
                baseUiModel.postValue(BaseUiModel(showLoading = true))
                this@TracDetailViewModel.barcode = barcode
                val result = repository.trugTracCodgIsGather(Gson().toJson(TraceRequest(barcode,"1")))
                if (result is Result.Success){
                    if (result.data.data.isGather){
                        if(result.data.data.drugDictInfo==null){
                            baseUiModel.postValue(BaseUiModel(showLoading = false,showError = "未找到与溯源码匹配的药品,请手动选中到待扫描的药品"))
                        }
                        else{
                            var indexTemp = -1
                            if(prescriptioninfo.isNotEmpty()){
                                run layer@{
                                    prescriptioninfo[0].drugInfoList.forEachIndexed  { index, drugInfoBean ->
                                        result.data.data.drugDictInfo.forEach { resultDrugDictInfo ->
                                            if (resultDrugDictInfo.drugCode == drugInfoBean.drugCode) {
                                                indexTemp = index
                                                lastIndex = selectIndex.value ?: -1
                                                selectIndex.postValue(index)
                                                return@layer
                                            }
                                        }
                                    }
                                }
                            }
                            //选中的时候就算没有查到也要去往里面加
                            if (selectIndex.value!=-1){
                                selectIndex.postValue(selectIndex.value)
                                baseUiModel.postValue(BaseUiModel(showLoading = false))
                            }else{
                                if (indexTemp==-1){
                                    baseUiModel.postValue(BaseUiModel(showLoading = false,showError = "未找到与溯源码匹配的药品,请手动选中到待扫描的药品"))
                                }else{
                                    baseUiModel.postValue(BaseUiModel(showLoading = false))
                                }
                            }

                        }
                    }else{
                        baseUiModel.postValue(BaseUiModel(showLoading = false,showError = result.data.data.gatherMsg))
                    }

                }else if (result is Result.Error){
                    baseUiModel.postValue(BaseUiModel(showLoading = false,showError = result.errorData?:result.exception.message))
                }
            }
        }
    }

    /**
     * 保存数据
     */
    fun finishScanDrugCode(finishRequest: FinishAdviceRequest){
        viewModelScope.launch(Dispatchers.Main) {
            withContext(Dispatchers.IO) {
                baseUiModel.postValue(BaseUiModel(showLoading = true))
                val result = repository.finishScanDrugCode(GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().toJson(finishRequest))
                if (result is Result.Success){
                    baseUiModel.postValue(BaseUiModel(showLoading = false,showSuccess = true))
                    barcode = ""
                    prescriptioninfo = mutableListOf()
                    Prescriptionbarcode = ""
                    lastIndex = -1
                    canAdd = false
                }else if (result is Result.Error){
                    baseUiModel.postValue(BaseUiModel(showLoading = false,showError = result.errorData?:result.exception.message))
                }
            }
        }
    }
}